package com.jeff.tianti.common;

import com.jeff.tianti.cms.entity.ColumnInfo;
import com.jeff.tianti.cms.service.ColumnInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ColumnInfoCom {
    @Autowired
    private ColumnInfoService columnInfoService;
    /**
     * @Ceator:liuYI
     * @Describe:根据传进来的父code/id获取对应子cms_column_info的name并封装map key:code value:name  流操作
     */
    public Map findColumnInfoList(String parentCodeOrId) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(parentCodeOrId)) {
            List<ColumnInfo> all = getList(parentCodeOrId);
            if (all != null && all.size() > 0) {
                all.stream().forEach(t -> map.put(t.getId(), t.getName()));
            }
        }
        return map;
    }

    /**
     * @Ceator:liuYI
     * @Describe: 根据传进来的父code/id获取对应子cms_column_info集合
     */
    public List<ColumnInfo> getList(String parentCodeOrId) {
        List<ColumnInfo> all = new ArrayList<>();
        if (StringUtils.isNotBlank(parentCodeOrId)) {
            all = columnInfoService.findAll(new Specification<ColumnInfo>() {
                @Override
                public Predicate toPredicate(Root<ColumnInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    Predicate p1 = null;
                    if (parentCodeOrId.length() < 32) {
                        p1 = cb.equal(root.get("parent").get("code"), parentCodeOrId);//所有父的code
                    } else {
                        p1 = cb.equal(root.get("parent").get("id"), parentCodeOrId);//所有父的id
                    }
                    query.orderBy(cb.asc(root.get("orderNo").as(Integer.class)));
                    Predicate p = cb.and(p1);
                    return p;
                }
            });
        }
        return all;
    }
}
